package net.kleinhenz.droidshop;

import java.util.List;

import net.kleinhenz.droidshop.R;
import net.kleinhenz.droidshop.model.Price;
import net.kleinhenz.droidshop.model.Product;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.database.DataSetObserver;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

public class ProductActivity extends Activity implements ListAdapter 
{
	private Product product = null;
	private ListView priceListView = null;
	
	private ImageFetcherThread imageFetcherThread = null;
	
	private Handler handler = new Handler() {
	    @Override
        public void handleMessage(android.os.Message msg) 
	    {
	    	if (msg.what==ImageFetcherThread.OK)
	    	{
	    		ImageView productImage = ((ImageView)findViewById(R.id.ProductImage));
	    		productImage.setImageDrawable(imageFetcherThread.getResult());
	    		productImage.setAdjustViewBounds(true);
	    		productImage.setOnClickListener(new OnClickListener() {
	    			@Override
	    			public void onClick(View v) 
	    			{
	    				ImageView view = new ImageView(v.getContext());
	    				view.setAdjustViewBounds(true);
	    				view.setImageDrawable(imageFetcherThread.getResult());
	    				view.setMaxHeight(350);
	    				view.setMaxWidth(220);

	    				new AlertDialog.Builder(v.getContext())
	                    .setTitle(getResources().getString(R.string.product_image))
	                    .setPositiveButton(android.R.string.ok, null)
	                    .setView(view)
	                    .show();
	    			}
	    		});
	    	}
        }
	};
	
	@Override
	protected void onCreate(Bundle savedInstanceState) 
	{
		super.onCreate(savedInstanceState);
		
		Log.d("DroidShop", "Tabbed product activity started.");				

		setContentView(R.layout.product);

		this.product = (Product)getIntent().getExtras().get("product");		
		DroidShopTabsActivity.addToList(this, ListFactory.LIST_HISTORY, this.product);
		
		priceListView = (ListView)findViewById(R.id.ProductPrices);
		priceListView.setAdapter(this);
		priceListView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) 
			{
				Uri uri = Uri.parse(product.getPrices().get(position).getBuyLink().toString());
				startActivity(new Intent(Intent.ACTION_VIEW, uri)); 
			}			
		});

		((TextView)findViewById(R.id.ProductName)).setText(product.getName());
		((TextView)findViewById(R.id.ProductTypeAuthor)).setText(adaptLocale(product.getType(), getResources().getString(R.string.locale)) + ", " + product.getAuthor());
		((TextView)findViewById(R.id.ProductDescription)).setText(product.getDescription());

		LinearLayout ratingLayout = ((LinearLayout)findViewById(R.id.ProductRatingLayout));
		createStars(ratingLayout, product.getStars());
		
		Log.d("DroidShop", "Fetching product image.");		
		imageFetcherThread = new ImageFetcherThread(this, handler, product.getImageLink());
		imageFetcherThread.start();		
	}

	@Override
	protected void onDestroy() 
	{
		super.onDestroy();
		if (imageFetcherThread.getResult() instanceof BitmapDrawable)
			((BitmapDrawable)imageFetcherThread.getResult()).getBitmap().recycle();
	}

	@Override
	public boolean onMenuItemSelected(int featureId, MenuItem item)
	{
		return getParent().onMenuItemSelected(featureId, item);
	}
	
	public static void createStars(LinearLayout rootLayout, double rating)
	{
		int numOn = (int)Math.floor(rating);
		int numHalve = rating-numOn>0?1:0;
		int numOff = 5-numOn-numHalve;
		
		for (int i=0; i<numOn; i++)
			rootLayout.addView(createStarImageView(rootLayout, 0));
		if (numHalve==1)
			rootLayout.addView(createStarImageView(rootLayout, 1));			
		for (int i=0; i<numOff; i++)
			rootLayout.addView(createStarImageView(rootLayout, 2));
	}
	
	public static ImageView createStarImageView(View root, int state)
	{
		ImageView thisStar = new ImageView(root.getContext());
		if (state==0)
			thisStar.setImageResource(R.drawable.star_on);
		else if (state==1)
			thisStar.setImageResource(R.drawable.star_halve);
		else
			thisStar.setImageResource(R.drawable.star_off);
		return thisStar;		
	}

	@Override
	public boolean areAllItemsEnabled() 
	{
		return true;
	}

	@Override
	public boolean isEnabled(int position) 
	{
		return true;
	}

	@Override
	public int getCount() 
	{
		return 1;
	}

	@Override
	public Object getItem(int position) 
	{
		return product.getPrices().get(getBestPricePosition(product.getPrices()));
	}

	@Override
	public long getItemId(int position) 
	{
		return position;
	}

	@Override
	public int getItemViewType(int position) 
	{
		return 0;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) 
	{
		return getBestPriceView();
	}

	@Override
	public int getViewTypeCount() 
	{
		return 1;
	}

	@Override
	public boolean hasStableIds() 
	{
		return true;
	}

	@Override
	public boolean isEmpty() 
	{
		if (getBestPriceView()==null)
			return true;
		else
			return false;
	}

	@Override
	public void registerDataSetObserver(DataSetObserver observer) 
	{
		// NOP - set never changes
	}

	@Override
	public void unregisterDataSetObserver(DataSetObserver observer) 
	{
		// NOP - set never changes
	}
	
	private View getBestPriceView()
	{
		int position = getBestPricePosition(product.getPrices());
		if (position>-1)
		{
			// FIXME: use different layout here
			LinearLayout layout = (LinearLayout)LayoutInflater.from(this).inflate(R.layout.bestprice, null, false);
			Price thisPrice = product.getPrices().get(position);
			
			TextView merchantView = (TextView)layout.findViewById(R.id.Merchant);
			TextView priceView = (TextView)layout.findViewById(R.id.Price);
			TextView availabilityView = (TextView)layout.findViewById(R.id.Availability);

			ImageView logoView = (ImageView)layout.findViewById(R.id.AmazonLogo);
			if (thisPrice.getMerchant().equalsIgnoreCase("amazon.com"))
			{
				logoView.setImageDrawable(getResources().getDrawable(R.drawable.amazoncom));
				((LinearLayout)layout.findViewById(R.id.MerchantImage)).removeView(merchantView);
			}
			else if (thisPrice.getMerchant().equalsIgnoreCase("amazon.co.uk"))
			{
				logoView.setImageDrawable(getResources().getDrawable(R.drawable.amazoncouk));
				((LinearLayout)layout.findViewById(R.id.MerchantImage)).removeView(merchantView);
			}
			else if (thisPrice.getMerchant().equalsIgnoreCase("amazon.de"))
			{
				logoView.setImageDrawable(getResources().getDrawable(R.drawable.amazonde));
				((LinearLayout)layout.findViewById(R.id.MerchantImage)).removeView(merchantView);
			}
			else 
			{
				logoView.setImageDrawable(getResources().getDrawable(R.drawable.amazonmarket));
				merchantView.setText(thisPrice.getMerchant().length()>25?thisPrice.getMerchant().substring(0, 25):thisPrice.getMerchant());
			}

			priceView.setText(PricesActivity.createPriceString(thisPrice.getFormattedPrice(), getResources().getString(R.string.locale)));
			availabilityView.setText(thisPrice.getAvailability().trim());
			
			return layout;			
		}
		else 
			return null;
	}

	private int getBestPricePosition(List<Price> prices)
	{
		int currentLowestPos = -1;
		double currentLowestValue = -1;

		// FIXME: the main menu can only be activated (to go to history) when the exchange rates are loaded completely
		double euroUsd = DroidShop.currency.get("USD");
		double euroGbp = DroidShop.currency.get("GBP");

		for (int i=0; i<prices.size(); i++)
		{			
			String formattedPrice = prices.get(i).getFormattedPrice();
			double currentValue = Double.parseDouble(formattedPrice.replaceAll("[^0-9]*([0-9]{1,2}[.,][0-9]{1,2})[^0-9]*", "$1").replace(',', '.'));
			if (formattedPrice.contains("$"))
				currentValue = currentValue/euroUsd;
			else if (formattedPrice.contains("£"))
				currentValue = currentValue/euroGbp;			

			if (currentLowestValue==-1 || currentValue<currentLowestValue) 
			{
				currentLowestPos = i;
				currentLowestValue = currentValue;
			}
		}

		return currentLowestPos;
	}

	private String adaptLocale(String type, String locale)
	{
		if (locale!=null && locale.equalsIgnoreCase("DE"))
			if (type!=null && type.equals("Book"))
				return "Buch";
			else if (type!=null && type.equals("Video Games"))
				return "Videospiel";
			else
				return type;
		else
			return type;		
	}
}
